//
//  SocketObject.m
//  SocretTest
//
//  Created by ellenpage on 12-11-23.
//  Copyright (c) 2012年 ellenpage. All rights reserved.
//

#import "Constant.h"
#import "GCDAsyncSocket.h"
#import "SocketObject.h"

@interface SocketObject ()<GCDAsyncSocketDelegate>


@end

@implementation SocketObject
@synthesize gcdSocket;

static SocketObject *sharedSocketObject = nil;

+ (SocketObject *)sharedInstance
{
    @synchronized(self)
    {
        if (sharedSocketObject == nil)
        {
            sharedSocketObject = [[self alloc] init];
        }
    }
    return  sharedSocketObject;
}

- (void)startConnection
{
    dispatch_queue_t mainQ = dispatch_get_main_queue();
    self.gcdSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:mainQ];
    
    NSError *err = nil;
    if(![self.gcdSocket connectToHost:[PassValueClass sharedIntance].ipStr onPort:[kSocketPort integerValue] error:&err])
    {
        NSLog(@"SocretFail");
    }
    else
    {
        NSLog(@"SocretOK");
        [self.gcdSocket acceptOnPort:[kSocketPort integerValue] error:nil];
    }
}


#pragma mark - SocketDelegate - Socket代理

-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(socketIsConnected)])
    {
        [self.delegate socketIsConnected];
    }
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
    NSLog(@"socket = %@",err);
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(socketIsDisConnected)])
    {
        [self.delegate socketIsDisConnected];
    }
}

-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(socketIsReadData:tag:)])
    {
        [self.delegate socketIsReadData:data tag:tag];
    }
}

-(void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(socketIsWriteData:)])
    {
        [self.delegate socketIsWriteData:tag];
    }
}

@end
